<script setup>
import {
    Edit,
    Delete,
    Plus
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { lessonCategoryListService, lessonCategoryAddService, lessonCategoryUpdateService, lessonCategoryDeleteService } from '@/api/lesson.js'
import { uploadFileService } from '@/api/upload.js'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const tokenStore = useTokenStore()
const categorys = ref([])

// 获取分类列表
const lessonCategoryList = async () => {
    try {
        let result = await lessonCategoryListService()
        if (result.code === 0) {
            categorys.value = result.data
        } else {
            ElMessage.error(result.msg || '获取分类列表失败')
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
    }
}

// 初始加载分类列表
lessonCategoryList()

// 控制添加分类弹窗
const dialogVisible = ref(false)
const title = ref('')

// 添加分类数据模型
const categoryModel = ref({
    categoryName: '',
    categoryAlias: '',
    categoryImage: ''
})

// 表单ref
const formRef = ref(null)

// 表单校验规则
const rules = {
    categoryName: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
    ],
    categoryAlias: [
        { required: true, message: '请输入分类别名', trigger: 'blur' },
        { min: 2, max: 15, message: '长度在2到15个字符', trigger: 'blur' }
    ],
    categoryImage: [
        { required: true, message: '请上传分类图片', trigger: 'change' }
    ]
}

// 处理图片上传
const handleUpload = async (file) => {
    if (!file) {
        ElMessage.error('上传文件不能为空！')
        return false
    }

    // 检查文件类型
    const isImage = file.raw && file.raw.type && file.raw.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
    }
    
    // 检查文件大小（限制为2MB）
    const isLt2M = file.raw.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    try {
        const formData = new FormData()
        formData.append('file', file.raw)
        const response = await uploadFileService(formData)
        if (response.code === 0) {
            categoryModel.value.categoryImage = response.data
            ElMessage.success('图片上传成功')
        } else {
            ElMessage.error(response.msg || '图片上传失败')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败，请稍后重试')
    }
    return false // 阻止自动上传
}

// 添加分类
const addCategory = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 检查是否为管理员
                if (tokenStore.userRole !== 2) {
                    ElMessage.error('只有管理员可以添加分类')
                    return
                }

                const result = await lessonCategoryAddService(categoryModel.value)
                if (result.code === 0) {
                    ElMessage.success('添加成功')
                    await lessonCategoryList()
                    dialogVisible.value = false
                    clearData()
                } else {
                    ElMessage.error(result.msg || '添加失败')
                }
            } catch (error) {
                console.error('添加分类失败:', error)
                ElMessage.error('添加分类失败，请稍后重试')
            }
        }
    })
}

// 展示编辑弹窗
const showDialog = (row) => {
    dialogVisible.value = true
    title.value = row ? '编辑分类' : '添加分类'
    if (row) {
        categoryModel.value = { ...row }
    } else {
        clearData()
    }
}

// 更新分类
const updateCategory = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const result = await lessonCategoryUpdateService(categoryModel.value)
                if (result.code === 0) {
                    ElMessage.success('修改成功')
                    await lessonCategoryList()
                    dialogVisible.value = false
                } else {
                    ElMessage.error(result.msg || '修改失败')
                }
            } catch (error) {
                console.error('修改分类失败:', error)
                ElMessage.error('修改分类失败，请稍后重试')
            }
        }
    })
}

// 删除分类
const deleteCategory = (row) => {
    ElMessageBox.confirm(
        '确认删除该分类吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const result = await lessonCategoryDeleteService(row.id)
            if (result.code === 0) {
                ElMessage.success('删除成功')
                await lessonCategoryList()
            } else {
                ElMessage.error(result.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除分类失败:', error)
            ElMessage.error('删除分类失败，请稍后重试')
        }
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 清空表单数据
const clearData = () => {
    categoryModel.value = {
        categoryName: '',
        categoryAlias: '',
        categoryImage: ''
    }
    if (formRef.value) {
        formRef.value.resetFields()
    }
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>课程分类</span>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisible=true;title='添加分类';clearData()">添加分类</el-button>
                </div>
            </div>
        </template>
        <el-table :data="categorys" style="width: 100%">
            <el-table-column label="序号" width="100" type="index" prop="id"> </el-table-column>
            <el-table-column label="分类图片" width="120">
                <template #default="{ row }">
                    <el-image :src="row.categoryImage" style="width: 80px; height: 80px" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column label="分类名称" prop="categoryName"></el-table-column>
            <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteCategory(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>

        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form ref="formRef" :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="分类名称" prop="categoryName">
                    <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="分类别名" prop="categoryAlias">
                    <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="分类图片" prop="categoryImage">
                    <el-upload
                        class="avatar-uploader"
                        action="#"
                        :show-file-list="false"
                        accept="image/*"
                        :auto-upload="false"
                        :on-change="handleUpload"
                    >
                        <img v-if="categoryModel.categoryImage" :src="categoryModel.categoryImage" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="title == '添加分类' ? addCategory() : updateCategory()">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>